<?php

namespace App\Http\Controllers\Manager;

use App\Helper;
use App\Http\Controllers\Controller;
use App\Models\ServerSpellMall;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CooperationController extends Controller
{
    public $prefix='manager.server';

    public function index($id){
        return view($this->prefix.'.cooperation',['id'=>$id]);
    }

    public function info($id){
        $server=$this->CheckServer($id);
        $server->user_acc_cooperation='';
        if ($server->user_id_cooperation>0){
            $user_coop=User::find($server->user_id_cooperation);
            if ($user_coop){
                $server->user_acc_cooperation=$user_coop->email;
            }
        }
        return JsonResponse::create(['err'=>0,'data'=>$server]);
    }

    public function saveConfig($id,Request $request){
        $server=$this->CheckServer($id);
        $acc=$request->get('acc');
        if ($acc==''){
            $server->user_id_cooperation=0;
            $server->cooperation_ratio=$request->get('ratio');
            $server->save();
            return JsonResponse::create(['err'=>0]);
        }
        if ($acc==Auth::user()->email){
            return JsonResponse::create(['err'=>-1,'msg'=>'不能添加自己']);
        }
        $user=User::where('email',$acc)->get()->toArray();
        if ($user){
            $server->user_id_cooperation=$user[0]['id'];
            $server->cooperation_ratio=$request->get('ratio');
            $server->save();
            return JsonResponse::create(['err'=>0]);
        }
        else{
            return JsonResponse::create(['err'=>-1,'msg'=>'未找到此用户']);
        }
    }
}
